<?php
namespace frontend\modules\Api\controllers;

use common\models\TallyRecord;
use common\models\User;
use common\services\ToolService;
use common\services\UserService;
use frontend\modules\Api\services\CommonService;
use Yii;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;

/**
 * Class UserController
 * @package frontend\modules\Api\controllers
 * 用户相关
 */
class UserController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 初始化方法
     */
    public function init()
    {
        parent::init();
    }

    /**
     * @throws
     * 返回用户信息
     */
    public function actionGetInfo()
    {
        $host = Yii::$app->request->hostInfo;
        $identity = Yii::$app->user->getIdentity();
        $userInfo = [
            'username' => $identity->username,
            'mobile'   => $identity->mobile,
            'email'    => $identity->email,
            'avatar'   => $identity->avatar ?: $host.'/static/images/default.png',
            'status'   => $identity->status,
            'vip_status'=>$identity->vip_status,
            'last_login_time' => $identity->last_login_time,
        ];
        return self::successResponse($userInfo);
    }

    /**
     * 用户资料修改 支持头像修改
     */
    public function actionEdit()
    {
        $user = Yii::$app->user->identity;
        $avatar   = Yii::$app->request->post('avatar',null);
        $username = Yii::$app->request->post('username',null);
        if($avatar) {
            $user->avatar = $avatar;
        }
        if($username) {
            $user->username = $username;
        }
        $result = $user->save();
        if($result) {
            return self::successResponse();
        }else{
            Yii::warning('修改资料失败;ID:'.$user->getId().';msg:'.current($user->getFirstErrors()));
            return self::failureResponse(500,current($user->getFirstErrors()));
        }
    }

    /**
     * @throws
     * 设置密码
     */
    public function actionSetPassword()
    {
        $form = DynamicModel::validateData([
            'password' => Yii::$app->getRequest()->post('password'),
        ],[
            ['password', 'required'],
            ['password', 'filter', 'filter' => 'trim'],
            ['password', 'string','min'=> 6,'max'=> 15],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        // 校验密码是否合理
        $uid = Yii::$app->user->identity->getId();
        try{
            UserService::setNewPassword($uid,$form->password);
            return self::successResponse();
        }catch (Exception $e){
            return self::failureResponse(500,$e->getMessage());
        }
    }

    /**
     * 首页统计报告
     * @throws
     */
    public function actionSummary()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId) {
            return self::failureResponse(500,'缺少账本参数');
        }
        $query = TallyRecord::find()->where([
            'uid' => $this->_user['id'],
            'tally_id' => $tallyId
        ]);
        // 收入和支出查询条件区分
        $whereIn  = ['in','type',[TallyRecord::TYPE_IN]];
        $whereOut = ['in','type',[TallyRecord::TYPE_OUT,TallyRecord::TYPE_TRANS]];
        // 今日收支
        $todayTime  = date('Y-m-d 00:00:00');

        $todayIn    = (clone $query)->andFilterWhere(['>','created_time',$todayTime])
                            ->andFilterWhere($whereIn)
                            ->sum('amount');
        $todayOut   = (clone $query)->andFilterWhere(['>','created_time',$todayTime])
                            ->andFilterWhere($whereOut)
                            ->sum('amount');
        // 本周收支
        list($weekBegin,$weekEnd) = ToolService::weekDateTime();
        $weekIn    = (clone $query)->andFilterWhere(['between','created_time',$weekBegin,$weekEnd])
            ->andFilterWhere($whereIn)
            ->sum('amount');
        $weekOut   = (clone $query)->andFilterWhere(['between','created_time',$weekBegin,$weekEnd])
            ->andFilterWhere($whereOut)
            ->sum('amount');
        // 本月收支
        list($monthBegin,$monthEnd) = ToolService::monthDateTime();
        $monthIn    = (clone $query)->andFilterWhere(['between','created_time',$monthBegin,$monthEnd])
            ->andFilterWhere($whereIn)
            ->sum('amount');
        $monthOut   = (clone $query)->andFilterWhere(['between','created_time',$monthBegin,$monthEnd])
            ->andFilterWhere($whereOut)
            ->sum('amount');
        return self::successResponse([
            'today'   => [
                'in'    => abs($todayIn),
                'out'   => abs($todayOut),
            ],
            'week'    => [
                'in'    => abs($weekIn),
                'out'   => abs($weekOut),
            ],
            'month' =>  [
                'in'    => abs($monthIn),
                'out'   => abs($monthOut)
            ],
        ]);
    }

    /**
     * @throws
     * 退出登录
     */
    public function actionLogout()
    {
        UserService::logoutByToken($this->token);
        return self::successResponse();
    }



    /**
     * 用户设置手机号
     */

    public function actionUserPhone(){
        $formData = Yii::$app->request->post();
        $old_phone = $this->_user['mobile'];
        if(!isset($formData['sms_code']) || empty($formData['sms_code'])){
            return self::failureResponse(500,'请填写验证码');
        }
        if(!CommonService::checkSmsCode($old_phone,$formData['sms_code'])) {
            return self::failureResponse(500,'验证码校验失败');
        }
        //判断如果没有手机号
        if(!isset($formData['mobile'])|| empty($formData['mobile'])){
            return  self::failureResponse(500,'没有新手机号');
        }
        $user_exits = User::findByUsername($formData['mobile']);
        if($user_exits){
            return self::failureResponse(500,'用户手机号已存在');
        }
        $user = Yii::$app->user->identity;
        $user->mobile = $formData['mobile'];
        $result = $user->save();
        if($result) {
            return self::successResponse();
        }else{
            Yii::warning('修改资料失败;ID:'.$user->getId().';msg:'.current($user->getFirstErrors()));
            return self::failureResponse(500,current($user->getFirstErrors()));
        }
    }
}
